import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Input, Modal, InputNumber, message } from 'antd';
import { SearchRow, SearchCol, SearchButton } from '@/styled/form';
import { DropDownSelect } from '@/components/DropDownSelect';
import { DICT } from '../enum';
import { exportExcl } from '@/utils/xlsx';
import XLSX from "xlsx";

interface IProps {
  current: number,
  form: any,
  dispatch?: Function,
  initCurrent: Function,
  new: boolean,
  dict?: Object,
  cond?: any,
  export: Function,
  create?: {
    data: Array<any>,
    message: string
  }
}

const FormItem = Form.Item;
const ONE_PAGE_SIZE = 10;

@connect(({ qrcode_blank }) => ({
  dict: qrcode_blank.dict,
  cond: qrcode_blank.cond,
  create: qrcode_blank.create || {},
}))
class Search extends Component<IProps> {

  state = {
    showCreateModel: false,
    showDownload: this.props.create.message === 'success',
    num: 1
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'qrcode_blank/queryDict',
      payload: {
        keyList: DICT
      }
    }).then(() => {
      const { cond, form } = this.props;
      const { pageNum, pageSize, ...searchParams } = cond;
      form.setFieldsValue(searchParams);
    });
  }

  static getDerivedStateFromProps(props, state) {
    const flag = props.create.message === 'success';
    if (flag !== state.showDownload) {
      return {
        showDownload: props.create.message === 'success'
      }
    }
  }

  search = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'qrcode_blank/updateCond',
          payload: {
            ...values
          }
        })

        this.props.initCurrent()
      }
    });
  };

  handleExport = e => {
    e.preventDefault();
    this.props.export()
  }

  showCreate = e => {
    e.preventDefault();

    this.setState({ showCreateModel: true })
  }

  createNum = num => {
    this.setState({ num })
  }

  showModal = () => {
    this.setState({ showCreateModel: true });
  };

  hideModal = () => {
    this.setState({ showCreateModel: false });
  };

  handleCreate = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'qrcode_blank/create', payload: this.state.num })
  }

  handleSubExport = () => {
    const { create = { data: [] } } = this.props;
    const { data } = create;
    const ans = data && Array.isArray(data) && data.map(item => {
      return {
        '二维码地址': item.code,
        '状态': '未绑定',
        '操作人员': item.creatorName,
        '操作时间': item.createTime,
      }
    });

    exportExcl({
      XLSX,
      data: ans,
      name: "空白二维码导出",
      fileName: "空白二维码导出"
    })

    this.hideSubModal()
  }

  hideSubModal = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'qrcode_blank/setCreateMsg', payload: 'close' })

    this.setState({ showCreateModel: false })
  }

  render() {
    const { dict = {}, form } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };

    return (
      <Form onSubmit={this.search}>
        <SearchRow>
          <SearchCol key={1} span={4}>
            <FormItem
              label="状态"
              {...formItemLayout}
            >
              {getFieldDecorator('bindStatus', {
                rules: [{ message: '状态' }],
              })(
                DropDownSelect(dict, 'qrcode.bind.status', '', '140px')
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={3} span={14}></SearchCol>
          <SearchCol key={4} span={6}>
            <SearchRow type="flex" justify="end">
              <SearchButton htmlType="submit">搜索</SearchButton>
              <SearchButton onClick={this.handleExport}>导出</SearchButton>
              <SearchButton type="primary" onClick={this.showCreate}>新增二维码</SearchButton>
            </SearchRow>
          </SearchCol>
          <Modal
            title="新增空白二维码"
            visible={this.state.showCreateModel}
            onOk={this.handleCreate}
            onCancel={this.hideModal}
            okText="确认"
            cancelText="取消"
            width={350}
          >
            <p>新增数量:</p>
            <InputNumber min={1} defaultValue={1} onChange={this.createNum} />
          </Modal>
          <Modal
            title="操作成功"
            visible={this.state.showDownload}
            onOk={this.handleSubExport}
            onCancel={this.hideSubModal}
            okText="确定"
            cancelText="取消"
            width={200}
          >
            <p>是否需要导出二维码?</p>
          </Modal>
        </SearchRow>
      </Form>
    );
  }
}

const SearchS = Form.create<IProps>()(Search);
export default SearchS;
